#! /bin/bash

bname=`basename $0`
usage="$bname --help \t\t\t\t\t\t\t\t - shows this\n$bname repeat_count [input_files] [sim_params] [\"+\"versions]  \t\t - run the 'input_files' test inputs (delimitered with space) for 'repeat_count' times, for specified vefisons and simulation parameters, as follows:\n\tversion - one of systemc versions or \"all\"\n\tsim_params - following simulation parameters are available:\n\t-t [ --use-threads ]  whether to use threads (or methods otherwise)\n\t-s [ --sim-time ] arg simulation time, in ms\nFor example:\n\t$bname 10 ./input/* --sim-time=10 +basic +orig"

if [ ! -n "$*" ]
then
	echo  -e $usage
	exit
fi

case $1 in '-h'|'-help'|'--help')
	echo  -e $usage
	exit;;
esac


repeat_count=$1; shift

red='\E[31;47m'
green='\E[32;47m'
yellow='\E[33;30m'
cyan='\E[36;47m'

cecho(){
	echo -e "$1""$2"
	tput sgr0
}

fail=" \E[31;47mFAIL"
pass=" \E[32;47mPASS"
report_prefix(){
	echo -n '[ '$1' | '$2' ]'	
}
versions=`echo $* | grep -o "\+[[:graph:]]*[[:space:]]*" | sed "s|\+||" | xargs`
input_files=`echo $* | sed "s|[-+][[:graph:]]*[[:space:]]*||g"`
sim_params=`echo $* | grep -o "\-[[:graph:]]*[[:space:]]*" | xargs`
verbose=`echo $sim_params | grep -o '\-v' | xargs`

spawn_root=$SYSCPAR_ROOT/tests/spawn
precompiled=$spawn_root/precompiled_test.cpp
precompiled_inj=$spawn_root/precompiled_test_inj.cpp
inject_marker="int inject_here_some_unique_name;"


go(){
	#$1 is version
	if [[ -d $SYSCPAR_ROOT/code/$1 ]]; then
		test_executable=$spawn_root/spawn_$1

		#precompile
		rm -f $precompiled
		make precompile_$1

		for x in $input_files
		do
			#inject & compile
			sed "s|$inject_marker\;*|\#include \"macros.hpp\"\n \#include \"$x\"|" $precompiled > $precompiled_inj
			make compile_$1

			#run test
			fast_test $1 $x	
		done
		rm -f $precompiled $precompiled_inj $test_executable
	else
	 	cecho "Version '$1' not found"
	fi
}

run(){
	for ((i=1; i <= repeat_count ; i++))
	do
		$test_executable $sim_params | grep 'reporting' | wc -l
		echo -n '.' >&2
	done
}

fast_test(){
	#$1 is version
	#$2 is test filename

	report_prefix $1 $2
	num_lines=`run | uniq -c | tee 'tmp~' | wc -l`
	if (( num_lines == 0 )); then cecho "$red" "smth went really wrong, exiting"; exit 1; fi
	if (( num_lines > 1 ));	then cecho $fail ; else cecho $pass; fi
	[[ "$verbose" ]] && cat 'tmp~'
	rm -f 'tmp~'
}

[[ "$versions" == "all" ]] && { pushd $SYSCPAR_ROOT/code; versions=`echo *`; popd; }

for v in $versions; do go $v; done
make clean
